function ConvertAllFilesBackToTiff (sDirectory)
%%Convert Imaris files in sDirectory (and its subfolders) to tiff files

    function ConvertFolder(sDirectory,apImaris)
    %ConvertAllFiles(sDirectory,apImaris);
    %Expects a Directory as string and an instance of Imaris.
    %Directory will be searched recursively for *.ims files which will then be
    %converted to the OmeTiff file format.
    %
    % Hendrik Golzke and Patrik Rath
    % Last change: 2010-08-20
        sVersionString = '100820';


        lList=dir(sDirectory);

        for iFile=1:length(lList)
            sFilename=lList(iFile).name;
            %Don't go into . and ..
            if (isequal(sFilename,'.') || isequal(sFilename,'..'))
                continue;
            end;
            %Go into sub folders
            if (lList(iFile).isdir)
                sTempDir2=[sDirectory '\' lList(iFile).name];
                ConvertFolder(sTempDir2,apImaris);
                continue;
            end;
            if ( strcmp('.ims',sFilename(end-3:end)) )
                sFile=[sDirectory '\' sFilename];
                %Try to open file, if not display error
                try
                    apImaris.FileOpen(sFile);
                catch struError
                    disp(['Imaris ' struError.message]);
                end;

                %Test whether we opened the file
                try
                    bRightFile=isequal(apImaris.GetCurrentFileName,sFile);
                catch
                    disp(['Can''t open file: ' sFile]);
                    continue;
                end;
                if ( ~bRightFile )
                    disp(['Can''t open file: ' sFile]);
                else
                    %Danger you have to append an underscore at the end of the
                    %filename otherwise things are getting really strange with
                    %the Filewriter
                    sFilename= [sDirectory '\tif2ims2tif' sVersionString '\' sFilename(1:end-4) '_converted.tif'];
                    try
                        apImaris.FileSave(sFilename,'writer="OmeTiff"');
                    catch
                        disp(['Couldn''t save file: ' sFileName '.tif']);
                    end;
                end;
            end;
        end;
    end

    %Check whether user supplied sDirectory
    if (~exist(sDirectory,'var'))
        sDirectory = uigetdir('C:\','Choose folder whose files should be converted from .ims to .tif');
        if isequal(sDirectory,0)
            return;
        end;
    end;
    if ~isdir(sDirectory)
        return;
    end;
    apImaris = actxserver('Imaris.Application');
    ConvertFolder(sDirectory,apImaris);
end